class ReposDownloads
  attr_accessor :github

  def initialize(github)
    @github = github
  end

  def getDownloads(repo, user=nil)
    username = user == nil ? @github.username : user
    @github.get('repos/%s/%s/downloads' % [username, repo])
  end

  def getDownload(repo, id, user=nil)
    username = user == nil ? @github.username : user
    @github.get('repos/%s/%s/downloads/%s' % [username, repo, id])
  end

  def createDownload(repo, filePath, description=nil, content_type=nil, user=nil)
    puts 'user:%s' % @github.username
    puts 'password:%s' % @github.password
    # PART 1: Create the resource @ github
    username = user == nil ? @github.username : user
    params = {
        :name => Pathname.new(filePath).basename,
        :size => File.new(filePath).size,
        :description => description,
        :content_type => content_type
    }
    params = @github.removeEmptyParams(params)
    data = params.to_json
    resource = @github.post('repos/%s/%s/downloads' % [username, repo], data)
    # PART 2: Create the download @ Amazon s3
    response = RestClient.post(resource['s3_url'], [
        ['key', resource['path']],
        ['acl', resource['acl']],
        ['success_action_status', 201],
        ['Filename', resource['name']],
        ['AWSAccessKeyId', resource['accesskeyid']],
        ['Policy', resource['policy']],
        ['Signature', resource['signature']],
        ['Content-Type', resource['mime_type']],
        ['file', File.open(filePath)]
    ])
    if response.code == 201
      resource['html_url']
    else
      response.code
    end
  end

  def deleteDownload(repo, id, user=nil)
    username = user == nil ? @github.username : user
    @github.delete('repos/%s/%s/downloads/%s' % [username, repo, id],)
  end
end